#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Description:       :
@Date     :2021/11/19 23:31:43
@Author      :ying.chen
'''
from array import array
import math
from typing import Mapping


class Vector2d:
    __slots__ =('__x', '__y')
    typecode = 'd'

    def __init__(self, x, y) -> None:
        self.x = float(x)
        self.y = float(y)

    def __repr__(self) -> str:
        return '{}({!r}, {!r})'.format(type(self).__name__, *self)

    def __str__(self):
        return str(tuple(self))

    # 把Vector2d实例变成可迭代的对象，这样才能拆包（例如，x, y=my_vector）
    def __iter__(self):
        return (i for i in (self.x, self.y))

    # 生成字节序列
    def __bytes__(self):
        return (bytes([ord(self.typecode)]) + bytes(array(self.typecode, self)))

    # 构建元组进行比较
    def __eq__(self, other):
        return tuple(self) == tuple(other)

    def __abs__(self):
        return math.hypot(self.x, self.y)

    def __bool__(self):
        return bool(abs(self))
    def __hash__(self):
        return hash(self.x) ^ hash(self.y)

    @classmethod
    def frombytes(cls, octets):
        typecode = chr(octets[0])
        memv = memoryview(octets[1:]).cast(typecode)
        return cls(*memv)

if __name__ == '__main__':
    v1 = Vector2d(3, 4)
    c = bytes(v1)
    print(c)
    v2 = Vector2d.frombytes(c)
    print(v2)
    # print(v1)
    # x, y = v1
    # print(x, y)
    # print(repr(v1))
    # v2 = eval(repr(v1))
    # print(v2 == v1)
    # print(v2)
    # octets = bytes(v1)
    # print(octets)
    # print(abs(v1))
    # print(bool(v1))
    # print(bool(Vector2d(0, 0)))
